import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import {
  Drawer,
  Button,
  Spin,
  Form,
  Row,
  Col,
  Select,
  DatePicker,
  Input,
  message,
  InputNumber,
} from 'antd';

import { TRDefault } from '#/components/TRTheme/index.js';
import { HttpCode } from '#/utils/contacts.js';
import planIcon from '@/assets/img/plan_icon.png';

import { postXJContractDetail } from '../../service';
import type { ISearchFormData, IContractSourceType } from '../../type';
import { IDrawerType } from '../../type';
import { RadioGroup } from '../../components/index';
import { timeSliceOptions, userTypeOptions, powerTypeOptions } from '../../dictionary';
import styles from './index.less';
import moment from 'moment';

interface IProps {
  /**
   * 合约id
   */
  contractId?: string;
  /**
   * 刷新
   */
  flashKey?: number;
  /**
   *
   */
  stationId?: string;
  /**
   * 合约来源
   */
  contractSource?: IContractSourceType;
  /**
   * 抽屉的宽度
   */
  width?: string;
  /**
   * 表单选项值
   */
  searchFormData?: ISearchFormData;
  /**
   * 是否显示抽屉
   */
  visible?: boolean;
  /**
   * 关闭函数
   */
  onClose?: () => void;
  /**
   * 提交
   */
  onSubmit?: (data: any, isDdit: boolean) => any;
  /**
   * 抽屉展示的状态
   */
  drawerType?: IDrawerType;
  /**
   * 提交/取消按钮loading状态
   */
  isLoading?: boolean;
  /**选中的合约日期 */
  date?: string;
  /**选中的合约tag */
  tag?: string;
  /**省份下交易单元*/
  stationOptions?: any;
  /**自建合约id*/
  id?: any;
}

const XJDetail = (props: IProps) => {
  const [form] = Form.useForm();
  const {
    visible = false,
    width = '60%',
    drawerType = IDrawerType.ADD,
    isLoading = false,
    contractId,
    stationId,
    contractSource,
    date,
    tag,
    stationOptions: _stationOptions,
    onSubmit,
    onClose,
    id,
  } = props;
  const [data, setData] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<boolean>(false);
  const [stationName, setStationName] = useState<any>('');
  const [stationOptions, setStationOptions] = useState<any>([]);

  const isAllowEdit = drawerType !== IDrawerType.DETAIL; // 详情状态不允许编辑并且显示详情状态

  // 取消
  const _onCancel = () => {
    onClose && onClose();
  };

  // 提交按钮
  const _onSubmit = async () => {
    form.validateFields().then(async () => {
      const formData = form.getFieldsValue();
      const params = {
        ...data,
        ...formData,
        stationName,
        month: moment(formData?.month).startOf('M').format('YYYY-MM-DD'),
      };
      const res = onSubmit && (await onSubmit(params, drawerType === IDrawerType.EDIT));
      if (res && res.statusCode === HttpCode.SUCCESS) {
        _onCancel();
      }
    });
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { value, label } = option;
    return (
      value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  const onChangeStation = (e: any) => {
    const _obj = stationOptions.find((item: any) => item.value === e);
    setStationName(_obj?.label);
  };

  // 初始化数据
  const fetchData = async (params: {
    contractId?: string;
    contractSource?: IContractSourceType;
    stationId?: string;
  }) => {
    setData({});
    setLoading(true);
    setError(false);
    // 调取查询合约详情数据接口
    const res = await postXJContractDetail(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setData(res.data);
      form.setFieldsValue({
        ...res?.data,
        stationName,
        month: moment(data?.month),
        stationId: stationId + '',
      });
      setError(false);
    } else {
      setError(true);
      message.info(res?.message || '请求失败');
    }
    setLoading(false);
  };
  // 重置
  const onReset = () => {
    form.resetFields();
  };

  useEffect(() => {
    const stationList = _.flattenDeep(
      _stationOptions?.map((a: any) =>
        a?.children?.map((b: any) => ({ label: b.label, value: b.value })),
      ),
    );
    setStationOptions(stationList);
  }, [JSON.stringify(_stationOptions)]);

  useEffect(() => {
    if (drawerType !== IDrawerType.ADD && contractId && visible) {
      const params = {
        contractId,
        contractSource,
        stationId,
        date,
        tag,
        id,
      };
      onChangeStation(stationId);
      fetchData(params);
    } else {
      onReset();
    }
  }, [contractId, contractSource, stationId, visible]);

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
      取消
    </Button>,
    <Button
      key="dtest2"
      type="primary"
      onClick={_onSubmit}
      loading={isLoading}
      style={{ marginLeft: 16 }}
    >
      确定
    </Button>,
  ];

  const onInputChange = (e: any, fields: string, type = 0) => {
    const value = e && e > 0 ? parseFloat(parseFloat(e as any).toFixed(type ? 1 : 2)) : 0;
    form.setFieldsValue({
      [fields]: value,
    });
  };

  return (
    <Drawer
      width={width}
      className={styles.operateLogModal}
      visible={visible}
      onClose={_onCancel}
      destroyOnClose={true}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>
            {drawerType === IDrawerType.ADD
              ? '新建合约'
              : drawerType === IDrawerType.EDIT
              ? '编辑合约'
              : '合约详情'}
          </span>
        </div>
      }
      footer={drawerType === IDrawerType.DETAIL ? null : footerRender()}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin spinning={loading} />
        ) : error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : data ? (
          <div className={styles.content}>
            <Form
              className={isAllowEdit ? styles.form : styles.disabledForm}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
              form={form}
              colon={false}
              labelAlign="left"
              autoComplete="off"
              requiredMark={false}
            >
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={isAllowEdit ? 'stationId' : undefined}
                    label="场站"
                    rules={[{ required: true, message: '请输入场站名称' }]}
                  >
                    {isAllowEdit ? (
                      <Select
                        placeholder={'请选择场站名称'}
                        showArrow={true}
                        // disabled={drawerType === IDrawerType.EDIT}
                        options={stationOptions}
                        showSearch={true}
                        filterOption={filterOption as any}
                        onChange={onChangeStation}
                      />
                    ) : (
                      data?.stationName || '-'
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    name={isAllowEdit ? 'month' : undefined}
                    label="月份"
                    rules={[{ required: true, message: '请选择日期' }]}
                  >
                    {isAllowEdit ? (
                      <DatePicker style={{ width: '100%' }} picker="month" />
                    ) : (
                      data?.month || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item label="购电方" required>
                    {isAllowEdit ? (
                      <>
                        <Form.Item
                          name={isAllowEdit ? 'powerPurchaserName' : undefined}
                          rules={[{ required: true, message: '请选择购电方' }]}
                          className={styles.inlineCell}
                          style={{ margin: 0 }}
                        >
                          <Input placeholder="请输入名称" />
                        </Form.Item>
                        <Form.Item
                          name={isAllowEdit ? 'userType' : undefined}
                          rules={[{ required: true, message: '请选择类型' }]}
                          style={{ margin: '0 0 0 16px' }}
                          className={styles.inlineCell}
                        >
                          <Select
                            placeholder="请选择类型"
                            showArrow={true}
                            // disabled={drawerType === IDrawerType.EDIT}
                            options={userTypeOptions}
                            showSearch={true}
                            filterOption={filterOption as any}
                          />
                        </Form.Item>
                      </>
                    ) : (
                      (data?.powerPurchaserName || '-') +
                      '/' +
                      (userTypeOptions.find((t) => t.value == data?.userType)?.label || '-')
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    name={isAllowEdit ? 'sellerPurchaserName' : undefined}
                    label="售电方"
                    rules={[{ required: true, message: '请填写售电方名称' }]}
                  >
                    {isAllowEdit ? (
                      <Input placeholder="请填写售电方名称" />
                    ) : (
                      data?.sellerPurchaserName || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={isAllowEdit ? 'contractName' : undefined}
                    label="合同名称"
                    rules={[{ required: true, message: '请选择合同名称' }]}
                  >
                    {isAllowEdit ? (
                      <Input placeholder="请填写合同名称" />
                    ) : (
                      data?.contractName || '-'
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    name={isAllowEdit ? 'contractId' : undefined}
                    label="合同编号"
                    rules={[{ required: true, message: '请选择合同编号' }]}
                  >
                    {isAllowEdit ? <Input placeholder="请填写合同编号" /> : data?.contractId}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={isAllowEdit ? 'tradeSequenceName' : undefined}
                    label="交易序列"
                    rules={[{ required: true, message: '请填写交易序列名称' }]}
                  >
                    {isAllowEdit ? (
                      <Input placeholder="请填写交易序列名称" />
                    ) : (
                      data?.tradeSequenceName || '-'
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    name={isAllowEdit ? 'powerSourceType' : undefined}
                    label="电源类型"
                    rules={[{ required: true, message: '请选择电源类型' }]}
                  >
                    {isAllowEdit ? (
                      <Select
                        placeholder="请选择类型"
                        showArrow={true}
                        options={powerTypeOptions}
                        showSearch={true}
                        filterOption={filterOption as any}
                      />
                    ) : (
                      powerTypeOptions.find((t) => t.value == data?.powerSourceType)?.label || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={isAllowEdit ? 'tag' : undefined}
                    label="时段"
                    initialValue={'1'}
                    rules={[{ required: true, message: '请选择时段' }]}
                  >
                    {isAllowEdit ? (
                      <RadioGroup options={timeSliceOptions} />
                    ) : (
                      timeSliceOptions.find((item) => item.value == data?.tag)?.label || '-'
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item label="合约电价" required>
                    {isAllowEdit ? (
                      <>
                        <Form.Item
                          name={isAllowEdit ? 'contractPrice' : undefined}
                          rules={[{ required: true, message: '请填写合约电价' }]}
                          noStyle
                        >
                          <InputNumber<string>
                            stringMode
                            className={styles.inlineCell}
                            min="0"
                            step="0.1"
                            formatter={(value) => `${value}`}
                            parser={(value) => value!.replace('', '')}
                            onChange={(e) => {
                              onInputChange(e, 'contractPrice', 1);
                            }}
                          />
                        </Form.Item>
                        <span className={styles.unit}>元/MWh</span>
                      </>
                    ) : data?.contractPrice ? (
                      data?.contractPrice + '元/MWh'
                    ) : (
                      '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <Form.Item label="合约电量" required>
                    {isAllowEdit ? (
                      <>
                        <Form.Item
                          name={isAllowEdit ? 'contractQuantity' : undefined}
                          rules={[{ required: true, message: '请填写合约电量' }]}
                          noStyle
                        >
                          <InputNumber<string>
                            stringMode
                            className={styles.inlineCell}
                            min="0"
                            step="0.01"
                            formatter={(value) => `${value}`}
                            parser={(value) => value!.replace('', '')}
                            onChange={(e) => {
                              onInputChange(e, 'contractQuantity');
                            }}
                          />
                        </Form.Item>
                        <span className={styles.unit}>MWh</span>
                      </>
                    ) : data?.contractQuantity ? (
                      data?.contractQuantity + 'MWh'
                    ) : (
                      '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Drawer>
  );
};

export default XJDetail;
